package com.watson.threadlocal;

/**
 * @Description: TODO
 * @Author watson
 * @Date 2022/8/3 20:30
 * @Version 1.0
 */
class test1 {
    public static void main(String[] args) {
        test2 sn = new test2();
        // ③ 3个线程共享sn，各自产生序列号
        TestClient t1 = new TestClient(sn);
        TestClient t2 = new TestClient(sn);
        TestClient t3 = new TestClient(sn);
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}

public class test2 {
    // ①通过匿名内部类覆盖ThreadLocal的initialValue()方法，指定初始值
    private static ThreadLocal<Object> seqNum = new ThreadLocal<Object>() {
        @Override
        public Integer initialValue() {
            return 0;
        }
    };

    // ②获取下一个序列值
    public int getNextNum() {
        seqNum.set((Integer) seqNum.get() + 1);
        return (Integer) seqNum.get();
    }

}

class TestClient implements Runnable {
    private test2 sn;

    public TestClient(test2 sn) {
        super();
        this.sn = sn;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            // ④每个线程打出3个序列值
            System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + sn.getNextNum() + "]");
        }
    }
}
